package com.redare.dev.smart.generator.service.impl;

import com.redare.dev.smart.generator.sdk.OnlFormHeadSdk;
import com.redare.dev.smart.generator.sdk.parser.Parser;
import com.redare.dev.smart.generator.sdk.pojo.OnlFormField;
import com.redare.dev.smart.generator.sdk.pojo.OnlFormHead;
import com.redare.dev.smart.generator.sdk.pojo.form.OnlFormHeadForm;
import com.redare.dev.smart.generator.sdk.utils.StringUtils;
import com.redare.dev.smart.generator.service.service.OnlFormFieldService;
import com.redare.dev.smart.generator.service.service.OnlFormHeadService;
import com.redare.devframework.common.pojo.CommonResult;
import com.redare.devframework.common.pojo.Page;
import com.redare.devframework.common.utils.MapUtils;
import com.redare.devframework.common.validation.ValidationUtils;
import com.redare.devframework.sql.db.base.SpringJdbcHelper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * impl
 *
 * @author yangqiangyu
 * @date 2021-08-28 11:44:05
 */
@Service(value = "com.redare.dev.smart.generator.impl.OnlFormHeadSdkImpl")
public class OnlFormHeadSdkImpl implements OnlFormHeadSdk {

    @Autowired
    OnlFormHeadService onlFormHeadService;

    @Autowired
    OnlFormFieldService onlFormFieldService;

    @Autowired
    Parser parser;

    @Autowired
    SpringJdbcHelper jdbcHelper;


    @Override
    public CommonResult<Boolean> addOnlFormHead(OnlFormHeadForm.Add form) {
        CommonResult result = ValidationUtils.simpleValidate(form);
        if (result.isNotSuccess()) {
            return result;
        }
        boolean bool = onlFormHeadService.addOnlFormHead(form);
        return CommonResult.returnBoolWrapper(bool, "添加失败");
    }

    @Override
    public CommonResult<Boolean> parseAddOnlFormHeadByBean(OnlFormHeadForm.Parse form) {
        CommonResult result = ValidationUtils.simpleValidate(form);
        if (result.isNotSuccess()) {
            return result;
        }
        List<OnlFormHead> formHeads = null;
        try {
            formHeads = parser.parseSql(form.getSql());
        }catch (Exception e){
            e.printStackTrace();
            return CommonResult.returnFailsWrapper(e.getMessage());
        }
        if (CollectionUtils.isEmpty(formHeads)){
            return CommonResult.returnFailsWrapper("sql解析异常");
        }
        for (OnlFormHead formHead : formHeads) {
            formHead.setSysId(form.getSysId());
            formHead.setTableType(0);
        }
        boolean bool = onlFormHeadService.addOnlFormHeadByBean(formHeads);
        return CommonResult.returnBoolWrapper(bool, "添加失败");
    }

    @Override
    @Transactional
    public CommonResult<Boolean> syncAddOnlFormHeadByBean() {
        StringBuffer createSql  = new StringBuffer();
        List<Map<String,Object>> tables = this.jdbcHelper.getJdbcTemplate().queryForList("SHOW tables");
        for (Map<String, Object> table : tables) {
            Set<String> keySet = table.keySet();
            String tableName = null;
            for (String s : keySet) {
                tableName = (String) table.get(s);
                break;
            }
            if (StringUtils.isNotBlank(tableName)){
                Map tableInfo = this.jdbcHelper.getJdbcTemplate().queryForMap("SHOW CREATE TABLE "+tableName);
                String create_table = MapUtils.getString(tableInfo, "Create Table");
                createSql.append(create_table+";");
            }
        }
        if (StringUtils.isBlank(createSql)){
            return CommonResult.returnFailsWrapper("同步失败");
        }
        List<OnlFormHead> insertHeads = new ArrayList<>();
        List<OnlFormHead> formHeads = null;
        try {
            formHeads = parser.parseSql(createSql.toString());
        }catch (Exception e){
            if (e!=null){
                e.printStackTrace();
                return CommonResult.returnFailsWrapper(e.getMessage());
            }
        }
        if (CollectionUtils.isEmpty(formHeads)){
            return CommonResult.returnFailsWrapper("sql解析异常");
        }
        List<String> tableNames = new ArrayList<>();
        Map<String,OnlFormHead> tableHeads = new HashMap<>(formHeads.size());
        for (OnlFormHead formHead : formHeads) {
            formHead.setTableType(0);
            String tableName = formHead.getTableName();
            tableHeads.put(tableName,formHead);
            tableNames.add(tableName);
        }
        //查询已存在的表
        Map<String,Object> existingHead = new HashMap<>();
        List<OnlFormHead> existingFormHead = onlFormHeadService.findOnlFormHeadList(new OnlFormHeadForm.Search()
                .setTableNames(tableNames).setIncludeFields(true));
        //已存在的表做字段更新，排序
        if (CollectionUtils.isNotEmpty(existingFormHead)){
            for (OnlFormHead formHead : existingFormHead) {
                existingHead.put(formHead.getTableName(),1);
                OnlFormHead item = tableHeads.get(formHead.getTableName());
                if (item==null){
                    continue;
                }
                String comment = item.getComment();
                //如果备注有修改编辑备注
                if (StringUtils.isNotBlank(comment)&&!org.apache.commons.lang.StringUtils.equals(comment,formHead.getComment())){
                    onlFormHeadService.editOnlFormHead(new OnlFormHeadForm.Edit()
                            .setId(formHead.getId()).setComment(comment));
                }
                List<OnlFormField> newFields = item.getFields();
                //遍历字段设置排序
                for (int i = 0; i < item.getFields().size(); i++) {
                    item.getFields().get(i).setOrderNum(i);
                }
                Map<String,OnlFormField> fieldMap = new HashMap<>(newFields.size());
                for (OnlFormField newField : newFields) {
                    fieldMap.put(newField.getField(),newField);
                }

                List<OnlFormField> insertFields = new ArrayList<>();
                List<OnlFormField> updateFields = new ArrayList<>();


                //获取数据库已存在的字段
                List<OnlFormField> fields = formHead.getFields();
                Map<String,OnlFormField> oldFieldsMap = new HashMap<>(newFields.size());

                if (CollectionUtils.isNotEmpty(fields)){
                    for (OnlFormField field : fields) {
                        oldFieldsMap.put(field.getField(),field);
                        OnlFormField formField = fieldMap.get(field.getField());
                        //老字段不在新字段里，做删除操作
                        if (formField==null){

                        }
                    }
                }
                for (OnlFormField newField : newFields) {
                    OnlFormField formField = oldFieldsMap.get(newField.getField());
                    if (formField==null){
                        //解析字段不在旧版本的数据库中
                        insertFields.add(newField.setFormHeadId(formHead.getId()));
                    }else{
                        //解析字段已存在，做更新操作
                        updateFields.add(newField.setId(formField.getId()));
                    }
                }
                onlFormFieldService.addOnlFormField(insertFields);
                for (OnlFormField updateField : updateFields) {
                    onlFormFieldService.editOnlFormFieldByBean(updateField);
                }
            }
        }

        for (OnlFormHead formHead : formHeads) {
            Object o = existingHead.get(formHead.getTableName());
            if (o==null){
                insertHeads.add(formHead);
            }
        }

        boolean bool = onlFormHeadService.addOnlFormHeadByBean(insertHeads);
        return CommonResult.returnSuccessWrapper();
    }

    @Override
    public CommonResult<Boolean> editOnlFormHead(OnlFormHeadForm.Edit form) {
        CommonResult result = ValidationUtils.simpleValidate(form);
        if (result.isNotSuccess()) {
            return result;
        }
        boolean bool = onlFormHeadService.editOnlFormHead(form);
        return CommonResult.returnBoolWrapper(bool, "编辑失败");
    }

    @Override
    public CommonResult<Boolean> deleteOnlFormHead(OnlFormHeadForm.Del form) {
        CommonResult result = ValidationUtils.simpleValidate(form);
        if (result.isNotSuccess()) {
            return result;
        }
        boolean bool = onlFormHeadService.deleteOnlFormHead(form);
        return CommonResult.returnBoolWrapper(bool, "删除失败");
    }

    @Override
    public CommonResult<List<OnlFormHead>> findOnlFormHeadList(OnlFormHeadForm.Search form) {
        List<OnlFormHead> list = onlFormHeadService.findOnlFormHeadList(form);
        return CommonResult.returnSuccessWrapper(list);
    }

    @Override
    public CommonResult<List<OnlFormHead>> findOnlFormHeadList(OnlFormHeadForm.Search form, int curPage, int pageSize) {
        List<OnlFormHead> list = onlFormHeadService.findOnlFormHeadList(form, curPage, pageSize);
        return CommonResult.returnSuccessWrapper(list);
    }

    @Override
    public CommonResult<Page<OnlFormHead>> findOnlFormHeadPage(OnlFormHeadForm.Search form, int curPage, int pageSize) {
        Page<OnlFormHead> page = onlFormHeadService.findOnlFormHeadPage(form, curPage, pageSize);
        return CommonResult.returnSuccessWrapper(page);
    }

    @Override
    public CommonResult<OnlFormHead> getOnlFormHead(OnlFormHeadForm.Get form) {
        CommonResult result = ValidationUtils.simpleValidate(form);
        if (result.isNotSuccess()) {
            return result;
        }
        OnlFormHead info = onlFormHeadService.getOnlFormHead(form);
        if (info == null) {
            return CommonResult.returnFailsWrapper("数据不存在");
        }
        return CommonResult.returnSuccessWrapper(info);
    }


}

